/**
 * Copyright (c) 2018-2028, Chill Zhuang 庄骞 (smallchill@163.com).
 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springblade.modules.auth.granter;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import lombok.AllArgsConstructor;
import org.springblade.core.tool.utils.DigestUtil;
import org.springblade.core.tool.utils.Func;
import org.springblade.modules.auth.enums.BladeUserEnum;
import org.springblade.modules.auth.utils.SsoAesUtil;
import org.springblade.modules.system.entity.Param;
import org.springblade.modules.system.entity.User;
import org.springblade.modules.system.entity.UserInfo;
import org.springblade.modules.system.service.IParamService;
import org.springblade.modules.system.service.IUserService;
import org.springframework.stereotype.Component;

import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * PasswordTokenGranter
 *
 * @author Chill
 */
@Component
@AllArgsConstructor
public class UserKeyTokenGranter implements ITokenGranter {

	public static final String GRANT_TYPE = "userKey";

	private IUserService userService;

	private IParamService iParamService;

	@Override
	public UserInfo grant(TokenParameter tokenParameter) {
		String userKey = tokenParameter.getArgs().getStr("userKey");
		UserInfo userInfo = null;
		if (Func.isNoneBlank(userKey)) {

			LambdaQueryWrapper<Param> lambdaQueryWrapper = new LambdaQueryWrapper<>();
			lambdaQueryWrapper.eq(Param::getParamKey,"account.sso");
			Param param = iParamService.getOne(lambdaQueryWrapper);
			if(param!=null){
				LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
				try {
					String dateStr = LocalDate.now().format(DateTimeFormatter.ofPattern("dd"));
					String aesKey = dateStr.charAt(0)+param.getParamValue()+dateStr.charAt(1);
					userLambdaQueryWrapper.eq(User::getAccount, SsoAesUtil.decrypt(userKey,aesKey));
				} catch (Exception e) {
					e.printStackTrace();
				}
				User user = userService.getOne(userLambdaQueryWrapper);
				if (user!=null){
					userInfo = userService.userInfo(user.getId());
				}
			}
		}
		return userInfo;
	}

}
